package com.roy.netty.sworddemo.server;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyNettyServer {
	private ServerBootstrap bootstrap;
	private TransportSettings transportSettings = new TransportSettings();
	private NettyServerChannelInitializer channelInitializer = new NettyServerChannelInitializer(transportSettings);
	
	public MyNettyServer() {
		EventLoopGroup bossGroup = new NioEventLoopGroup(transportSettings.getBossThreads());
        EventLoopGroup workerGroup = new NioEventLoopGroup(transportSettings.getWorkerThreads());
        Class<? extends ServerChannel> channelClazz = NioServerSocketChannel.class;
        if (transportSettings.isNativeEpoll()) {
            channelClazz = EpollServerSocketChannel.class;
        }
        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(channelClazz)
                .childHandler(channelInitializer)
                .option(ChannelOption.SO_BACKLOG, transportSettings.getSoBacklog())
                .option(ChannelOption.SO_REUSEADDR, transportSettings.isSoReuseAddress())
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.TCP_NODELAY, transportSettings.isTcpNoDelay())
                .childOption(ChannelOption.SO_KEEPALIVE, transportSettings.isSoKeepAlive())
                .childOption(ChannelOption.SO_SNDBUF, transportSettings.getSoSendBufferSize())
                .childOption(ChannelOption.SO_RCVBUF, transportSettings.getSoReceiveBufferSize())
                .childOption(ChannelOption.SO_REUSEADDR, transportSettings.isSoReuseAddress());
	}
	
	public void start() throws InterruptedException {
		System.out.println("开始创建netty连接");
		InetSocketAddress address = new InetSocketAddress(transportSettings.getBindAddress(),transportSettings.getPort());
		ChannelFuture future = bootstrap.bind(address).sync();
		System.out.println("netty server 启动成功,IP : "+transportSettings.getBindAddress()+";port "+transportSettings.getPort());
		future.channel().closeFuture().sync();
		System.out.println("NettyTCPServer channel closed.");
	}

	public void stop() {
		System.out.println("Stopping NettyTCPServer....");
		channelInitializer.getEngineHandlerExecutor().shutdownGracefully();
		if(bootstrap != null) {
			bootstrap.childGroup().shutdownGracefully();
			bootstrap.group().shutdownGracefully();
		}
		System.out.println("NettyTCPServer stopped....");
	}

}
